package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.BabyAllResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteMiniEditText;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.util.ChZhRJUtils;

import java.util.ArrayList;
import java.util.List;

public class PetnameListActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener {
    private String type, result_back, sex, xuexing, chengwei, shenfen, quanxian, neirong, permission,zidingyi;
    private ArrayList<String> list_relationship, list_sex, list_xuexing, list_shenfen, list_quanxian, list_neirong;
    private ListView listView;
    private int click_p = -1, index = -1;
    private MyAdapter myAdapter;
    private CuteEditText editText;
    private boolean canEdit = false;
    private BabyAllResponse babyAllResponse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_petname_list);
        listView = (ListView) findViewById(R.id.petname_listview);
        list_relationship = new ArrayList<String>();
        list_sex = new ArrayList<String>();
        list_xuexing = new ArrayList<String>();
        list_shenfen = new ArrayList<String>();
        list_quanxian = new ArrayList<String>();
        list_neirong = new ArrayList<String>();

        list_relationship.add("妈妈");
        list_relationship.add("爸爸");
        list_relationship.add("奶奶");
        list_relationship.add("爷爷");
        list_relationship.add("姥姥");
        list_relationship.add("姥爷");
        list_relationship.add("自定义");

        list_sex.add("男");
        list_sex.add("女");
        list_sex.add("未知");

        list_xuexing.add("A");
        list_xuexing.add("B");
        list_xuexing.add("AB");
        list_xuexing.add("O");

        list_shenfen.add("家长");
        list_shenfen.add("成员");

        list_quanxian.add("一起记");
        list_quanxian.add("围观");

        list_neirong.add("从加入后");
        list_neirong.add("全部");
        list_neirong.add("从孕期");
        list_neirong.add("从成长期");

        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.petname_list_cutetoolbar);
        toolbar.setOnClickCuteToolbarListener(this);

        myAdapter = new MyAdapter();
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        if (type.equals("relationship")) {
            chengwei = intent.getStringExtra("relationship");
            result_back = chengwei;
            Log.e("chengwei", chengwei);
            toolbar.setCuteTitle(ChZhRJUtils.getText(getIntent().getStringExtra("title"), "您与宝宝的关系"));
            switch (chengwei) {
                case "妈妈":
                    click_p = 0;
                    zidingyi = "";
                    myAdapter.notifyDataSetChanged();
                    break;
                case "爸爸":
                    click_p = 1;
                    zidingyi = "";
                    myAdapter.notifyDataSetChanged();
                    break;
                case "奶奶":
                    click_p = 2;
                    zidingyi = "";
                    myAdapter.notifyDataSetChanged();
                    break;
                case "爷爷":
                    click_p = 3;
                    zidingyi = "";
                    myAdapter.notifyDataSetChanged();
                    break;
                case "姥姥":
                    click_p = 4;
                    zidingyi = "";
                    myAdapter.notifyDataSetChanged();
                    break;
                case "姥爷":
                    click_p = 5;
                    zidingyi = "";
                    myAdapter.notifyDataSetChanged();
                    break;
                default:
//                    if (!chengwei.equals("")) {
                        list_relationship.set(list_relationship.size() - 1, chengwei);
//                    }
                    canEdit =true;
//                    index = 6;
                    zidingyi = chengwei;
                    click_p = 6;
                    myAdapter.notifyDataSetChanged();
                    break;
            }
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    result_back = list_relationship.get(position);
                    click_p = position;
                    myAdapter.notifyDataSetChanged();
                    if (position == list_relationship.size() - 1) {
                        editText = (CuteEditText) view.findViewById(R.id.tv_itemcolor);
                        openNameDialog();
                        /*canEdit = true;
                        editText = (CuteEditText) view.findViewById(R.id.tv_itemcolor);
                        editText.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                if (event.getAction() == MotionEvent.ACTION_UP) {
                                    editText.setText("");
                                    index = position;
                                }
                                return false;
                            }
                        });
                        result_back = list_relationship.get(position);
                        click_p = position;
                        myAdapter.notifyDataSetChanged();
//                result_back = list_relationship.get(position);
//                click_p = position;
//                myAdapter.notifyDataSetChanged();
                    } else {
                        index = position;
                        if (zidingyi.equals("")){
                            list_relationship.set(6,"自定义");
                        }else{
                            list_relationship.set(6,zidingyi);
                        }
                        canEdit = false;
                        result_back = list_relationship.get(position);
                        click_p = position;
                        myAdapter.notifyDataSetChanged();*/

                    }
//                    if (position == list_relationship.size()-1){
//                        openNameDialog();
//                    }
                }
            });
        } else if (type.equals("sex")) {
            toolbar.setCuteTitle("宝宝性别");
            sex = intent.getStringExtra("sex");
            int state = intent.getIntExtra("state", -1);
            if (state == 2) {
                list_sex.remove(2);
            }
            result_back = sex;
            switch (sex) {
                case "男":
                    click_p = 0;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "女":
                    click_p = 1;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "未知":
                    click_p = 2;
                    myAdapter.notifyDataSetChanged();
                    break;
                default:
                    click_p = -1;
                    myAdapter.notifyDataSetChanged();
                    break;
            }
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    result_back = list_sex.get(position);
                    click_p = position;
                    myAdapter.notifyDataSetChanged();
                }
            });
        } else if (type.equals("parent_sex")) {
            toolbar.setCuteTitle("性别");
            sex = intent.getStringExtra("sex");
            list_sex.remove(2);
            result_back = sex;
            switch (sex) {
                case "男":
                    click_p = 0;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "女":
                    click_p = 1;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "未知":
                    click_p = 2;
                    myAdapter.notifyDataSetChanged();
                    break;
                default:
                    click_p = -1;
                    myAdapter.notifyDataSetChanged();
                    break;
            }
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    result_back = list_sex.get(position);
                    click_p = position;
                    myAdapter.notifyDataSetChanged();
                }
            });
        } else if (type.equals("xuexing")) {
            toolbar.setCuteTitle("宝宝血型");
            xuexing = intent.getStringExtra("xuexing");
            result_back = xuexing;
            switch (xuexing) {
                case "A":
                    click_p = 0;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "B":
                    click_p = 1;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "AB":
                    click_p = 2;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "O":
                    click_p = 3;
                    myAdapter.notifyDataSetChanged();
                    break;
                default:
                    click_p = -1;
                    myAdapter.notifyDataSetChanged();
                    break;
            }
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    result_back = list_xuexing.get(position);
                    click_p = position;
                    myAdapter.notifyDataSetChanged();
                }
            });
        } else if (type.equals("shenfen")) {
            toolbar.setCuteTitle("身份");
            shenfen = intent.getStringExtra("shenfen");
            result_back = shenfen;
            switch (shenfen) {
                case "家长":
                    click_p = 0;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "成员":
                    click_p = 1;
                    myAdapter.notifyDataSetChanged();
                    break;
                default:
                    click_p = -1;
                    myAdapter.notifyDataSetChanged();
                    break;
            }
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (position == 0){
                        tip(4);
                    }else if (position == 1){
                        tip(5);
                    }
                    result_back = list_shenfen.get(position);
                    click_p = position;
                    myAdapter.notifyDataSetChanged();
                }
            });
        } else if (type.equals("quanxian")) {
            toolbar.setCuteTitle("日记权限");
            quanxian = intent.getStringExtra("quanxian");
            result_back = quanxian;
            switch (quanxian) {
                case "一起记":
                    click_p = 0;
                    myAdapter.notifyDataSetChanged();
                    break;
                case "围观":
                    click_p = 1;
                    myAdapter.notifyDataSetChanged();
                    break;
                default:
                    click_p = -1;
                    myAdapter.notifyDataSetChanged();
                    break;
            }
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    result_back = list_quanxian.get(position);
                    click_p = position;
                    myAdapter.notifyDataSetChanged();
                }
            });
        } else if (type.equals("neirong")) {
            toolbar.setCuteTitle("日记内容");
            neirong = intent.getStringExtra("neirong");
            result_back = neirong;
            String userId = intent.getStringExtra("userid");
            int babyId = intent.getIntExtra("babyID", -1);
            Baby baby = DatabaseManager.getInstance(this).queryBaby(userId, babyId);
//            babyAllResponse = get(permission, BabyAllResponse.class);
//            switch ( babyAllResponse.getAuth().getRange()){
//                case 0: // 加入
//                    btnAdd.setTwoState();
//                    break;
//                case 1: // 备孕期
//                    btnReady.setTwoState();
//                    break;
//                case 2: // 孕期
//                    btnStart.setTwoState();
//                    break;
//                case 3: // 成长期
//                    btnGrow.setTwoState();
//                    break;
//            }
            list_neirong.clear();

            if (Client.EMPTY_TIME != baby.getLastDate()) {
                list_neirong.add("从备孕期");
            }
            if (Client.EMPTY_TIME != baby.getDueDate()) {
                list_neirong.add("从孕期");
            }
            if (Client.EMPTY_TIME != baby.getBirthday()) {
                list_neirong.add("从成长期");
            }
            list_neirong.add("从加入后");
            for (int i = 0; i < list_neirong.size(); i++) {
                if (neirong.equals(list_neirong.get(i))) {
                    click_p = i;
                    myAdapter.notifyDataSetChanged();
//                    case "从加入后":
//                        click_p = 0;
//                        myAdapter.notifyDataSetChanged();
//                        break;
//                    case "从备孕期":
//                        click_p = 1;
//                        myAdapter.notifyDataSetChanged();
//                        break;
//                    case "从孕期":
//                        click_p = 2;
//                        myAdapter.notifyDataSetChanged();
//                        break;
//                    case "从成长期":
//                        click_p = 3;
//                        myAdapter.notifyDataSetChanged();
//                        break;
//                    default:
//                        click_p = -1;
//                        myAdapter.notifyDataSetChanged();
//                        break;
                }
            }

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                    mLoginInfo = Config.getLoginInfo(PetnameListActivity.this);
//                    String userId = mLoginInfo.getUserID();
//                    String phone = mLoginInfo.getPhone();
//                    String token = mLoginInfo.getToken().getAccessToken();
//                    final int babyId = mLoginInfo.getBabyID();
//                    BabyAndParent babyAndParent = DatabaseManager.getInstance(PetnameListActivity.this).queryBabyAndParent(userId, babyId);
//                    Baby babys = DatabaseManager.getInstance(PetnameListActivity.this).queryBaby(userId, babyId);
//                    switch (babys.getState()){
//                        case Client.STATE_READY:
//
//                            break;
//                        case Client.STATE_START:
//                            mDay = getBabyDay(babys);
//                            break;
//                        case Client.STATE_END:
//                            mDay = getBabyDay(babys);
//                            break;
//                    }
                    result_back = list_neirong.get(position);
                    click_p = position;
                    myAdapter.notifyDataSetChanged();
                }
            });
        }

        listView.setAdapter(myAdapter);

    }

    @Override
    public void onClickLeft() {
        onBackPressed();
    }

    @Override
    public void onClickRight() {
        Intent resultIntent = new Intent();
        if (type.equals("relationship")) {
            if (click_p == 6) {
                result_back = editText.getText().toString();
            }
            resultIntent.putExtra("relationship", result_back);
        } else if (type.equals("sex") || type.equals("parent_sex")) {
            resultIntent.putExtra("sex", result_back);
        } else if (type.equals("xuexing")) {
            resultIntent.putExtra("xuexing", result_back);
        } else if (type.equals("shenfen")) {
            resultIntent.putExtra("shenfen", result_back);
        } else if (type.equals("quanxian")) {
            resultIntent.putExtra("quanxian", result_back);
        } else if (type.equals("neirong")) {
            resultIntent.putExtra("neirong", result_back);
        }
        setResult(RESULT_OK, resultIntent);
        finish();
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (type.equals("relationship")) {
                return list_relationship.size();
            } else if (type.equals("sex") || type.equals("parent_sex")) {
                return list_sex.size();
            } else if (type.equals("xuexing")) {
                return list_xuexing.size();
            } else if (type.equals("shenfen")) {
                return list_shenfen.size();
            } else if (type.equals("quanxian")) {
                return list_quanxian.size();
            } else if (type.equals("neirong")) {
                return list_neirong.size();
            } else {
                return 0;
            }
        }

        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            View view = null;
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                view = View.inflate(PetnameListActivity.this, R.layout.item_textview_selector, null);
                holder.tv = (CuteEditText) view.findViewById(R.id.tv_itemcolor);
                holder.imageView = (ImageView) view.findViewById(R.id.iv_blue_selected);

                view.setTag(holder);
            } else {
                view = convertView;
                holder = (ViewHolder) view.getTag();
            }
//            if (position == list_relationship.size()-1){
//                holder.tv.setFocusable(true);
//                holder.tv.setClickable(true);
//            }else{
//                holder.tv.setFocusable(false);
//                holder.tv.setClickable(false);
//            }
            if (type.equals("relationship")) {
                holder.tv.setText(list_relationship.get(position));
            } else if (type.equals("sex") || type.equals("parent_sex")) {
                holder.tv.setText(list_sex.get(position));
            } else if (type.equals("xuexing")) {
                holder.tv.setText(list_xuexing.get(position));
            } else if (type.equals("shenfen")) {
                holder.tv.setText(list_shenfen.get(position));
            } else if (type.equals("quanxian")) {
                holder.tv.setText(list_quanxian.get(position));
            } else if (type.equals("neirong")) {
                holder.tv.setText(list_neirong.get(position));
            }
            if (click_p == position) {
                holder.tv.setTextColor(android.graphics.Color.parseColor("#c851f6"));
                holder.imageView.setVisibility(View.VISIBLE);
            } else {
                holder.tv.setTextColor(Color.BLACK);
                holder.imageView.setVisibility(View.INVISIBLE);
            }
            /*if (canEdit && position == list_relationship.size() - 1) {
                holder.tv.setEnabled(true);
                holder.tv.setFocusable(true);
                holder.tv.setClickable(true);
                holder.tv.setFocusableInTouchMode(true);
                holder.tv.requestFocus();
//                holder.tv.setText("");
//                holder.tv.requestFocusFromTouch();
//                holder.tv.setText("");
            } else {
                holder.tv.setFocusable(false);
                holder.tv.setClickable(false);
                holder.tv.setFocusableInTouchMode(false);
//                holder.tv.setText(list_relationship.get(position));
            }
//            holder.tv.setOnTouchListener(new View.OnTouchListener() {
//                @Override
//                public boolean onTouch(View v, MotionEvent event) {
//                    if (event.getAction() == MotionEvent.ACTION_UP) {
//
//                        index = position;
//                    }
//                    return false;
//                }
//            });
            if (type.equals("relationship")) {
                if (index != -1 && index == list_relationship.size()-1 && position==6) {
                    // 如果当前的行下标和点击事件中保存的index一致，手动为EditText设置焦点。
                    editText.requestFocus();

                    editText.setText("");

                }else{
                    if (index !=-1 && canEdit ) {
                        editText.clearFocus();
//                        if (chengwei.equals("")) {
//                            editText.setText("自定义");
//                        }else{
//                            editText.setText(chengwei);
//                        }
                    }
                }
//                } else {
//                    holder.tv.clearFocus();
//                    holder.tv.setText(list_relationship.get(position));
//                }
            }*/

            return view;
        }

        class ViewHolder {
            TextView tv;
            ImageView imageView;
        }
    }

    private void openNameDialog() {
//        final CuteEditText editText = new CuteEditText(PetnameListActivity.this);
//        editText.setText("自定义");
//        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = (PetnameListActivity.this).getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_select_role, null);
        final CuteTextView cuteTitle = (CuteTextView) view.findViewById(R.id.role_title);
        final CuteMiniEditText cuteName = (CuteMiniEditText) view.findViewById(R.id.role_name);
        cuteTitle.setText(ChZhRJUtils.getText(getIntent().getStringExtra("title"), "您与宝宝的关系"));
        cuteName.setText(editText.getText().toString());
        cuteName.setSelection(editText.getText().toString().length());
        builder.setView(view);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                list_relationship.remove(list_relationship.size() - 1);
                list_relationship.add(cuteName.getText().toString());
                result_back = cuteName.getText().toString();

            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        AlertDialog dialog = builder.create();
        dialog.show();
//        new AlertDialog.Builder(PetnameListActivity.this).setTitle("宝宝名称").setView(editText)
//                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
////                mSelectBaby.setText(editText.getText().toString());
////            getBaby().setName(editText.getText().toString());
////            mTextHead.setText(getBaby().getName() + "  /  " + getBabyDay(getBaby()));
//                        list_relationship.remove(list_relationship.size() - 1);
//                        list_relationship.add(editText.getText().toString());
//                    }
//                }).setNegativeButton("取消", null).show();
    }

    private void tip(int i) {
        Intent intent = new Intent(this, TipDialogActivity.class);
        intent.putExtra("state", i);
        startActivity(intent);
    }
}
